package com.zzf.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.zzf.commonutils.R;
import com.zzf.servicebase.exceptionhandler.GuliException;
import com.zzf.vod.service.VodService;
import com.zzf.vod.utils.ConstantVodUtils;
import com.zzf.vod.utils.InitVodClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("eduvod/video")
@Api(description = "视频管理")
@CrossOrigin
public class VodController {
    @Autowired
    private VodService vodService;

    @ApiOperation("上传视频")
    @PostMapping("uploadAlyVideo")
    public R uploadAlyVideo(MultipartFile file) {
        String videoId = vodService.uploadVideoAly(file);
        return R.ok().data("videoId", videoId);
    }

    //根据视频id删除阿里云视频
    @ApiOperation("删除视频")
    @DeleteMapping("removeAlyVideo/{id}")
    public R removeAliVideo(@PathVariable String id) {
        try {
//初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.KEY_ID, ConstantVodUtils.KEY_SECRET);
//创建删除视频的热quest对象
            DeleteVideoRequest request = new DeleteVideoRequest();
//向Request设置id
            request.setVideoIds(id);
            client.getAcsResponse(request);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "删除视频失败");
        }
    }

    //批量删除视频
    @DeleteMapping("delete-batch")
    public R deleteBatch(@RequestParam("videoIdList") List<String> videoIdList) {
        vodService.removeMoreAlyVideo(videoIdList);
        return R.ok();
    }

    //获取视频播放凭证
    @GetMapping("getPlayAuth/{id}")
    public R getPlayAuth(@PathVariable String id) {
        try {
//获取阿里云存储相关常量
            String accessKeyId = ConstantVodUtils.KEY_ID;
            String accessKeySecret = ConstantVodUtils.KEY_SECRET;
//初始化
            DefaultAcsClient client = InitVodClient.initVodClient(accessKeyId, accessKeySecret);
//请求
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            request.setVideoId(id);
//响应
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
//得到播放凭证
            String playAuth = response.getPlayAuth();
//返回结果
            return R.ok().message("获取凭证成功").data("playAuth", playAuth);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GuliException(20001, "获取凭证失败");
        }
    }
}
